package com.lcifn.middleware.rpc.serializer;

import com.lcifn.middleware.rpc.spi.ServiceSupport;

import java.util.HashMap;
import java.util.Map;

/**
 * 序列化支持类
 * @author lichao
 * @date 2021/1/31 17:13
 */
public class SerializerSupport {

    private static Map<Class<?>/*序列化对象类型*/, Serializer<?>/*序列化实现*/> serializerMap = new HashMap<>();

    static {
        for (Serializer serializer : ServiceSupport.loadAll(Serializer.class)) {
            serializerMap.put(serializer.getSerializeClass(), serializer);
        }
    }

    public static <E> byte[] serialize(E entry) {
        Serializer<E> serializer = (Serializer<E>) serializerMap.get(null);
        if (serializer == null) {
            throw new RuntimeException("Not found serializer of " + entry.getClass());
        }

        byte[] bytes = serializer.serialize(entry);
        return bytes;
    }

    public static <E> E deserialize(byte[] bytes, Class<E> clazz) {
        Serializer<E> serializer = (Serializer<E>) serializerMap.get(null);
        if (serializer == null) {
            throw new RuntimeException("Not found serializer of " + clazz);
        }
        return serializer.deserialize(bytes, clazz);
    }
}
